<?php

// Namespace

namespace Loop;


/**
 * CMathHelper is a helper that contains various functions to help developers deal with maths
 *
 * @package		Loop
 * @category	Helper
 */

class CMathHelper
{
	/**
	 * Calculate the coordinates (longitude/latitude) of a point equidistant from 3 apexes
	 * 
	 * @param 	array 	$boundingBox 	The array of apexes' coordinates
	 * @param 	float 	$longitude 	 	The longitude
	 * @param 	float 	$latitude 		The latitude
	 */

	public function convertBoundingBox($boundingBox, &$longitude, &$latitude)
	{
		// We'll need those 3 apexes

		$apex1 = $boundingBox[0];
		$apex2 = $boundingBox[1];
		$apex3 = $boundingBox[2];


		// What's the mid-lenght of each side?

		$distanceX = ($apex3[1] - $apex1[1]) / 2;
		$distanceY = ($apex2[0] - $apex1[0]) / 2; 


		// Add those lengths to obtain a central longitude/latitude

		$latitude = $apex1[1] + $distanceX;
		$longitude = $apex1[0] + $distanceY;
	}


	/**
	 * Calculates the linear regression
	 *
	 * @param 	array 	$x 			The array of abscissa
	 * @param 	array 	$y 			The array of ordinate
	 * @param 	float 	$slope 		The slope
	 * @param 	float 	$intercept	The intercept
	 */

	public function linearRegression($x, $y, &$slope, &$intercept)
	{
		// Do we have the same number of elements?

		$nbX = count($x);
		$nbY = count($y);

		if ($nbX != $nbY)
		{
			e
			(
				EXCEPTION_MATH_LINEAR_REGRESSION_FAILED,
				array
				(
					'nbX' => $nbX,
					'nbY' => $nbY
				)
			);
		}


		// Sum up x and y

		$sumOfX = array_sum($x);
		$sumOfY = array_sum($y);


		// Sum up the product of x and y

		$sumOfXX = 0;
		$sumOfXY = 0;

		for ($i = 0; $i < $nbX; $i++)
		{
			$sumOfXX += ($x[$i] * $x[$i]);
			$sumOfXY += ($x[$i] * $y[$i]);
		}


		// Calculate the slope

		$slope =
		(
			($nbX * $sumOfXY) - ($sumOfX * $sumOfY)
		)
		/
		(
			($nbX * $sumOfXX) - ($sumOfX * $sumOfX)
		);


		// Calculate the intercept

		$intercept = ($sumOfY - ($slope * $sumOfX)) / $nbX;
	}
}

?>
